<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas-demos</title>
    <style>
        * {
            margin: 0;
            padding: 0
        }
    </style>
</head>

<body>
<canvas id="cont">浏览器不支持</canvas>
<!--只能使用原生的js,如果让canvas左右居中使用display:block-->
<script>
    // 固定start获取画布
    const canvas = document.querySelector('#cont')
    // 获取画布上下文
    const ctx = canvas.getContext('2d')
    // 固定end

    const w = document.documentElement.clientWidth - 6
    const h = document.documentElement.clientHeight - 6
    canvas.width = w
    canvas.height = h

    function Ball(x, y) {
        this.x = x
        this.y = y
        this.r = 60
        // 随机颜色
        this.color = `rgb(${parseInt((Math.random() * 256).toString())},${parseInt((Math.random() * 256).toString())},${parseInt((Math.random() * 256).toString())})`
    }

    Ball.prototype.show = function () {
        // 半径减小
        this.r--
        // 画小球
        drawCircle(this.x, this.y, this.r, this.color)
    }


    /**
     * 画实心小球
     * @param x
     * @param y
     * @param r
     * @param color
     */
    function drawCircle(x, y, r, color = '#000') {
        ctx.beginPath()
        ctx.arc(x, y, r, 0, Math.PI * 2)
        ctx.fillStyle = color
        ctx.fill()
    }

    // 小球数组
    const ballArr = []
    // for (let i = 0; i < 5; i++) {
    //     const ball = new Ball(100 + i * 50, 100)
    //     ballArr.push(ball)
    // }

    /**
     * 鼠标移动事件
     * @param e
     */
    window.onmousemove = function (e) {
        const ball = new Ball(e.x, e.y)
        ballArr.push(ball)
    }
    const timer = setInterval(function () {
        ctx.clearRect(0, 0, w, h)
        for (let i = 0; i < ballArr.length; i++) {
            // 如果小球的半径小于0了,从数组中删除数据
            const ballArrElement = ballArr[i]
            if (ballArrElement.r <= 0) {
                ballArr.splice(i, 1)
            } else {
                ballArrElement.show()
            }
        }
    }, 10)

</script>
</body>
</html>
